<template>

	<view class="page">

		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">
			<uni-title type="h1" align="center" title="一 检查组队企业实施<医疗器械经营质量管理规范>的评价意见"></uni-title>
			
			 <view class="full-width-container">
			    <textarea 
			      @input="remarkInput" 
			      v-model="orderList.evaluationOpinion" 
			      class="full-width-textarea"
			      placeholder="请编辑评价意见"
			      :maxlength="500"
			    ></textarea>
			  </view>
		</uni-card>

		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">


			<mpopupHeaderRadioItem :show-bottom-border="true" label="检查组建议" :custom-class="'custom-align'"
				:custom-style="{ padding: '20rpx' }">
				<!-- 自定义右侧内容 -->
				<template>
					<uni-data-checkbox selectedColor="blue" selectedTextColor="blue" mode='list'
						v-model="orderList.medicalSuggestion" :localdata="processedMedicalItem"
						@change="onCheckboxChange"></uni-data-checkbox>
				</template>
			</mpopupHeaderRadioItem>
		</uni-card>

		<uni-card margin='2px' style="margin-bottom: 10px; padding: 5px;">

			<!-- 虚线容器 -->
			<view class="dashed-box2">

				<view class="custom-title">
					<view
						style="width:100px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:20px;">
						组长签名
					</view>

					<signInput :initialImage="orderList.groupLeaderSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl"></signInput>
				</view>
				<view class="custom-title">
					<view
						style="width:100px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:20px;">
						组员签名
					</view>

					<signInput :initialImage="orderList.teamMemberslSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl2"></signInput>
				</view>
				<view class="custom-title">
					<view
						style="width:100px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:20px;">
						观察员签名
					</view>

					<signInput :initialImage="orderList.observerSign" bgColor="#ffffff" :action="action"
						@signToUrl="signToUrl3"></signInput>
				</view>

				<!-- 动态签名列 -->
				<view v-for="(sign, index) in orderList.workOrderSignatureList" :key="index" class="custom-title">

					<view
						class="sign-text">
						{{sign.signaturePosition}}
					</view>

					<signInput :initialImage="sign.signature" bgColor="#ffffff" :action="action"
						@signToUrl="(url) => handleSignUpload(url, index)"></signInput>
				</view>

				<!-- 添加签名列按钮 -->
				<view class="dashed-box3" @click="addSignColumn">
					<text style="font-size: 20rpx;font-weight: bold;">+点此添加更多签字栏</text>
				</view>

				<!-- 核查人员日期 -->
				<view class="custom-dateText">
					<text @click="openDatePicker"
						class="custom-text3">{{ this.orderList.checkSignDate || '选择日期' }}</text>
				</view>
			</view>
		</uni-card>

<view v-if="editStatus!='FALSE'" class="button-container">
				<view class="button-save">
					<button style="flex: 1;" type="primary" @click="submitForm('1')">保存并提交检查报告</button>
				</view>
				<view class="button-save">
					<button style="flex: 1;" type="primary" @click="submitForm('0')">暂存</button>
				</view>
			</view>

		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopupf" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDialogConfirm" @close="handleDialogClose">
				<uni-datetime-picker type="date" @change="handleDateChange" />
			</uni-popup-dialog>
		</uni-popup>

		<!-- 添加日期选择弹窗 -->
		<uni-popup ref="datePopup" type="dialog">
			<uni-popup-dialog mode="base" title="选择日期" @confirm="handleDateConfirm" @close="handleDateClose">
				<uni-datetime-picker type="date" @change="handleDateChange2" />
			</uni-popup-dialog>
		</uni-popup>

		<!-- 添加备注输入弹窗 -->
		<uni-popup ref="inputPopup" type="dialog">
			<uni-popup-dialog mode="base" title="输入其他信息" @confirm="handleDialogConfirm2" @close="handleDialogClose2">
				<textarea @input="handleInput" v-model="remarkDialog" placeholder="请输入其他信息" style="padding: 10px;"
					auto-height :maxlength="-1"></textarea>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script>
	import signInput from "@/components/am-sign-input/am-sign-input.vue"
	import mpopupHeaderItem from "@/components/mpopup-header-item.vue"
	import mpopupHeaderRadioItem from "@/components/mpopup-header-radio-item.vue"
	import mpopupItem from "@/components/mpopup-item/mpopup-item.vue"
	import mpopupTable from "@/components/mpopup-table.vue"
	import {
		addMedical,
		getMedicalDict,
		medicalInfo,
		medicalGetInfo,
		medicalUpdate
	} from '@/api/order'
	import {
		getFoodReport
	} from '@/api/report.js'

	export default {
		components: {
			signInput,
			mpopupHeaderRadioItem
		},
		data() {
			return {
				textareaHeight: 56, // 初始单行高度
				remarkDialog: '',
				evaluationOpinion: '', //意见
				medicalSuggestion: '',
				medicalItem: [], // 核查人员日期
				currentIndex: -1, // 记录当前操作的选项索引
				formattedDate: '',
				parentSignList: [],
				workOrderId: '',
				groupLeaderSign: '',
				teamMemberslSign: '',
				observerSign: '',
				action: "https://8954wg323mw0.vicp.fun/app/upload/imageFile", //上传服务器的地址
				orderList: {
					evaluationOpinion: '',
					medicalSuggestion: '',
					workOrderSignatureList: [],
					correctionDate: '',
					checkSignDate: '',
					workOrderId: ''
				},
				editStatus: 'ADD',
				tempDate: '',
				tempDate2: ''
			}
		},
		onLoad(options) {
			if (options.editStatus != null) {
				const editStatus = decodeURIComponent(options.editStatus);
				const workOrderId = decodeURIComponent(options.workOrderId);

				this.orderList.workOrderId = workOrderId;
				this.editStatus = options.editStatus;
				this.getMedicalInfo(workOrderId);
			} else {
				const orderid = decodeURIComponent(options.workOrderId);
				this.orderList.workOrderId = orderid;

			}
			this.getMedicalDict('medical_suggestion')
		},

		computed: {
			processedMedicalItem() {
				return this.medicalItem.map(item => ({
					...item,
					text: item.date ? `${item.text}       应在（${item.date}）前完成整改` : item.text
				}));
			}
		},
		methods: {

			// 打开日期选择器
			openDatePicker() {
				this.$refs.datePopup.open();
			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;
			}, // 弹窗确认

			handleDialogConfirm() {
				if (this.tempDate) {
					const year = this.tempDate.getFullYear();
					const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					if (this.editDateType === 'checkPerson') {
						this.orderList.checkSignDate = formattedDate;
					} else {
						this.orderList.foodPersonDate = formattedDate;
					}
				}
				this.$refs.datePopupf.close();

			},

			// 日期变化暂存
			handleDateChange2(e) {
				this.tempDate2 = e ? new Date(e) : null;
			}, // 弹窗确认

			handleDateConfirm() {

				if (this.tempDate2) {
					const year = this.tempDate2.getFullYear();
					const month = (this.tempDate2.getMonth() + 1).toString().padStart(2, '0');
					const day = this.tempDate2.getDate().toString().padStart(2, '0');
					const formattedDate = `${year}-${month}-${day}`;
					this.orderList.checkSignDate = formattedDate;
				}
				this.$refs.datePopup.close();

			},

			// 添加签名列
			addSignColumn() {
				uni.showModal({
					title: '添加人员签名',
					content: '',
					editable: true, // 允许输入内容
					success: (res) => {
						if (res.confirm) {
							// 用户点击了“确定”
							const content = res.content || ''; // 获取输入的内容（如果允许输入）
							this.orderList.workOrderSignatureList.push({
								signature: '',
								signaturePosition: content, // 绑定输入的内容
								createBy: '系统管理员'
							});
						}
						// 用户点击“取消”则不做任何操作
					}
				});

			},

			// 处理签名上传（改造后）
			handleSignUpload(res, index) {
				try {
					const response = JSON.parse(res.data)
					console.log(response);
					if (response.code === 0) {
						this.$set(this.orderList.workOrderSignatureList, index, {
							...this.orderList.workOrderSignatureList[index],
							signature: response.data, // ✅ 正确提取data字段
						})
					} else {
						uni.showToast({
							title: response.msg,
							icon: 'none'
						})
					}
				} catch (e) {
					console.error('签名数据解析失败:', e)
					uni.showToast({
						title: '签名数据异常',
						icon: 'none'
					})
				}

				console.log('签名更新成功:', this.orderList.workOrderSignatureList)
			},
			// 获取医疗器械工单详情
			async getMedicalInfo(orderId) {

				const id = {
					workOrderId: orderId
				}
				const res = await medicalGetInfo(id);
				if (res.code === 0) {
					this.orderList = res.data;

				}
			},
			// 提交方法
			submitForm(status) {

				if (this.editStatus == 'FALSE') {
					// 处理失败情况
					uni.showToast({
						title: '当前处于查看状态',
						icon: 'none'
					});
				}

				if (this.editStatus === 'EDIT') {

					this.UPDATE(status);
				}

				if (this.editStatus === 'ADD') {
					this.ADD(status);
				}
			},
			// 提交方法
			async ADD(status) {
				this.orderList.auditStatus = status;
				const res = await addMedical(this.orderList);
				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '提交成功',
						icon: 'success',
						duration: 1500
					});
				// 关闭当前页面，跳转到工单页
				this.$closeAndRedirect({
				  url: '/pages/work/history/index'
				});
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},
			// 提交方法
			async UPDATE(status) {
				this.orderList.auditStatus = status;
				const res = await medicalUpdate(this.orderList);
				if (res.code === 0) {
					// 显示成功提示
					uni.showToast({
						title: '修改成功',
						icon: 'success',
						duration: 1500
					});
					// 1.5秒后返回上一页
					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						});
					}, 1500);
				} else {
					// 处理失败情况
					uni.showToast({
						title: res.msg || '提交失败',
						icon: 'none'
					});
				}

			},
			/**
			 * @param {Object} e
			 * 组长
			 */
			signToUrl(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				// 1. 解析响应数据（假设 e.data 是 JSON 字符串）
				const response = JSON.parse(e.data)
				this.orderList.groupLeaderSign = response.data;
			},
			/**
			 * @param {Object} e
			 * 组员
			 */
			signToUrl2(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				console.log(response.data);
				this.orderList.teamMemberslSign = response.data;

			},
			/**
			 * @param {Object} e
			 * 观察员
			 */
			signToUrl3(e) {
				if (e.error_code && e.error_code === '201') {
					uni.showToast({
						title: e.msg,
						icon: 'none'
					})
					return
				}
				const response = JSON.parse(e.data)
				this.orderList.observerSign = response.data;


			},
			handleSignListUpdate(updatedList) {
				this.parentSignList = updatedList // 接收子组件传递的数据[2,9](@ref)
			},
			handleToReprot() {
				console.log(this.parentSignList)
			},
			handleInput(e) {
				this.remarkDialog = e.detail.value.replace(/</g, '＜'); // 替换尖括号
			},
			remarkInput(e) {
				this.evaluationOpinion = e.detail.value.replace(/</g, '＜'); // 替换尖括号
			},
			handleDialogConfirm2() {
				// 更新对应选项的日期
				this.medicalItem[this.currentIndex].text = this.remarkDialog;
				this.orderList.remark=this.remarkDialog;
				this.$refs.inputPopup.close();
			},
			// 弹窗确认
			handleDialogConfirm() {
				const year = this.tempDate.getFullYear();
				const month = (this.tempDate.getMonth() + 1).toString().padStart(2, '0');
				const day = this.tempDate.getDate().toString().padStart(2, '0');
				this.formattedDate = `${year}-${month}-${day}`;
				// 更新对应选项的日期
				this.medicalItem[this.currentIndex].date = this.formattedDate;
				this.orderList.correctionDate = this.formattedDate;
				this.$refs.datePopupf.close();

			},
			// 日期变化暂存
			handleDateChange(e) {
				this.tempDate = e ? new Date(e) : null;

			},
			// 弹窗关闭
			handleDialogClose() {
				this.$refs.datePopupf.close();
			},
			// 弹窗关闭
			handleDialogClose2() {

				this.$refs.inputPopup.close();
			},


			handleDateClose() {
				this.$refs.datePopup.close();

			},
			onCheckboxChange(e) {
			  const value = e.detail.value;
			  // 找到选中项的索引
			  const index = this.medicalItem.findIndex(item => item.value === value);
			  
			  // 清除之前选项的特殊数据
			  if (this.previousIndex !== undefined) {
			    if (this.previousIndex === 2) {  // 如果是日期选项
			      this.medicalItem[this.previousIndex].date = '';  // 清空日期
			      this.orderList.correctionDate = '';  // 清空关联的日期字段
			    } else if (this.previousIndex === 3) {  // 如果是其他信息选项
			      this.medicalItem[this.previousIndex].text = this.medicalItem[this.previousIndex].text.split('（')[0];  // 还原原始文本
			      this.orderList.remark= ''; 
				  this.remarkDialog = '';  // 清空对话框内容
			    }
			  }
			
			  // 处理新选项
			  if (index === 2) { 
			    this.currentIndex = index;
			    this.$refs.datePopupf.open();
			  } else if (index === 3) { 
			    this.currentIndex = index;
			    this.$refs.inputPopup.open();
			  } else {
			    // 普通选项保持原始状态
			    this.medicalItem[index].date = '';
			    this.medicalItem[index].text = this.medicalItem[index].text.split('（')[0];
			  }
			
			  // 记录当前索引
			  this.previousIndex = index;
			  
			  // 强制更新视图（针对小程序等需要手动刷新的环境）
			  this.$forceUpdate();
			},
			//获取工单分类
			async getMedicalDict(type) {
				try {
					const res = await getMedicalDict(type)
					// 增加响应状态判断
					if (res.code === 0) {
						if (type === 'medical_suggestion') {
							this.medicalItem = res.data.map(item => ({
								text: item.label, // 注意字段名需与uni-data-select要求一致
								value: item.value,
								date: '' // 新增日期字段
							}))
						}

					} else {
						throw new Error(res?.data?.msg || '接口返回异常')
					}
				} catch (error) {
					uni.showToast({
						title: error.message || '获取失败',
						icon: 'none',
						duration: 2000
					})
				}
				console.log(this.medicalItem)
			},

		}

	}
</script>

<style lang="scss" scoped>
	.page {
		background-color: #e9f1fe;
		padding: 20px;
	}

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}



	/* 移动端适配 */
	@media (max-width: 768px) {
		.mpopup-body {
			overflow-x: auto;

			&-thead,
			&-tbody {
				min-width: 800px;
			}
		}
	}

	.date-text {
		font-size: 14px;
		text-decoration: underline;
		padding: 4rpx 8rpx;
	}

	.uni-column {
		padding: 20px;
		background-color: #e9f1fe;
		height: 160px;
		width: 100%;
		margin-top: 10px;
		margin-bottom: 20px;
		border-radius: 10px;
	}

	/* 虚线容器 */
	.dashed-box2 {
		width: 100%;
		margin: 24rpx auto;
		padding: 12rpx;
		border: 2rpx dashed #333;
		border-radius: 10rpx;
		background: #fff;
		margin-bottom: 40px;
		position: relative;

		&+.dashed-box {
			margin-top: 28rpx;
		}



	}

	.custom-title {
		display: flex;
		justify-content: center;
		align-items: center;
		margin-bottom: 10px;
		/* 保持原有下边距 */

	}

	/* 虚线容器 */
	.dashed-box3 {
		width: 100%;
		border: 2rpx dashed #0055ff;
		border-radius: 10rpx;
		background: #e5ecff;
		height: 120px;
		/* 设置为flex布局 */
		display: flex;
		/* 水平居中 */
		justify-content: center;
		/* 垂直居中 */
		align-items: center;
	}


	.custom-dateText {
		display: flex;
		margin: 20px;
		justify-content: flex-end;
		/* 子元素居左 */
	}

	.custom-text3 {
		border-bottom: 1px solid #000;
		padding-bottom: 2px;
		padding-left: 10px;
		color: #0055ff;
		font-size: 16px;

		font-weight: bold;
		padding-right: 10px;
		margin-left: 4px;
		margin-right: 4px;
	}
	
.full-width-container {
  width: 100%;
  position: relative;
  padding: 10rpx;
}

.full-width-textarea {
  width: 100%;
  background-color: #e9f1fe;
  height: 200rpx;
  padding: 20rpx;
  box-sizing: border-box;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  font-size: 19rpx;
  line-height: 1.6;
}

.sign-text{
	width:100px;color: black;font-size: 16px;font-weight: bold;text-align: right; margin-right:20px;
}
.button-container {
		display: flex;
		background-color: #ffffff;
		width: 100%;
		padding: 10px;
		flex-direction: column;
		/* 垂直排列 */
	
		.button-save {
			margin-bottom: 10px;
		}
	
		.button-child {
			display: flex;
			flex-direction: row;
			/* 垂直排列 */
	
		}
	}
</style>